<template>
  <div id="change_Avatar">
    <div class="CA_box">
      <div class="box_head">
        <span>修改头像</span>
        <i style="font-weight:bold;" class="el-icon-close" @click="complete"/>
      </div>
      <div class="box_body">
        <div class="upload_avatar">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <div class="ok_but">
          <el-button @click="complete" class="complete">完成</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "changeAvatar",
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    complete() {
      this.$emit('closeCA', 'changeAvatar')
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>

<style lang="less" scoped>
#change_Avatar {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 99;

  .CA_box {
    width: 500px;
    height: 40%;
    margin: 200px auto 0;
    background-color: #000000;
    border-radius: 10px;
    border: 1px solid #808080;

    .box_head {
      color: white;
      font-size: 20px;
      margin-top: 10px;

      span {
        font-family: songFont;
        margin-top: 20px;
        margin-left: 10px;
      }

      i {
        cursor: pointer;
        float: right;
        margin-right: 10px;

        &:hover {
          color: #808080;
        }
      }
    }

    .box_body {
      width: 400px;
      margin: 50px auto 0;

      .upload_avatar {
        display: flex;
        justify-content: center;
      }

      .ok_but {
        display: flex;
        justify-content: center;
        margin-top: 30px;

        .complete {
          width: 120px;
          color: black;
          font-weight: bold;
          background-color: #ffffff;
          border-color: #ffffff;

          &:hover {
            color: #808080;
          }
        }
      }
    }
  }
}
</style>
